// 获取元素
const H = document.querySelector('#h')
const M = document.querySelector('#m')
const S = document.querySelector('#s')
const ul = document.querySelector(".seckill ul")

// 秒杀倒计时
let date = new Date('2025-7-25 17:35:00')
let clock = setInterval(() => {time(date)}, 1000)

function time(date) {
  let now = new Date()
  let leftTime = date - now
  if (leftTime > 0) {
  let h = Math.floor(leftTime / 3600000)
  let m = Math.floor(leftTime / 60000) % 60
  let s = Math.floor(leftTime / 1000) % 60
  h = h < 10? '0' + h : h
  m = m < 10? '0' + m : m
  s = s < 10? '0' + s : s
  H.innerHTML = h;
  M.innerHTML = m;
  S.innerHTML = s;
  } else {
    H.innerHTML = '00';
    M.innerHTML = '00';
    S.innerHTML = '00';
    clearInterval(clock)
  }
}
time(date)
// 商品数据
obj = [{
        id: 1,
        name: '智能手机',
        price: 2999,
        image: './images/phone.webp',
        description: '最新款智能手机，搭载高性能处理器，6.5英寸全面屏，4800万像素四摄，5000mAh大电池。',
    },
    {
        id: 2,
        name: '笔记本电脑',
        price: 5999,
        image: './images/notebook.jfif',
        description: '轻薄笔记本电脑，第11代酷睿i5处理器，16GB内存，512GB固态硬盘，14英寸高清屏幕。',
    },
    {
        id: 3,
        name: '无线耳机',
        price: 899,
        image: './images/earphone.jfif',
        description: '真无线蓝牙耳机，主动降噪，通话降噪，长续航，IPX4防水，触控操作。',
    },
    {
        id: 4,
        name: '智能手表',
        price: 1299,
        image: './images/smartwatch.jfif',
        description: '多功能智能手表，心率监测，血氧检测，睡眠监测，50米防水，长达14天续航。',
    },
    {
        id: 5,
        name: '平板电脑',
        price: 3699,
        image: './images/pad.jfif',
        description: '10.9英寸全面屏平板，A14仿生芯片，4GB内存，64GB存储，支持Apple Pencil。',
    },
    {
        id: 6,
        name: '蓝牙音箱',
        price: 499,
        image: './images/bluetoothSpeaker.jfif',
        description: '便携式蓝牙音箱，360°环绕立体声，IPX7级防水，24小时续航，支持TWS双音箱串联。',
    }]

localStorage.setItem('commoditys', JSON.stringify(obj))

// 秒杀商品列表
function showCommoditys(id) {
    const commoditys = JSON.parse(localStorage.getItem('commoditys'))
    let li = document.createElement("li")
    li.innerHTML = `
        <img src="${commoditys[id-1].image}">
        <h4 class="name">${commoditys[id-1].name}</h4>
        <div class="price-area>
            <span class="price-seckill">￥${(commoditys[id-1].price * 0.8).toFixed(2)}</span>
            <span class="price-original">￥${(commoditys[id-1].price).toFixed(2)}</span>
        </div>
        <button disabled>立即抢购</button>
        `
    if (date <= new Date()) {
        li.children[3].setAttribute("class", "buy")
    } else {
        li.children[3].setAttribute("class", "no-buy")
    }
    ul.appendChild(li)
}
showCommoditys(1)
showCommoditys(2)
showCommoditys(3)

//秒杀按钮点击事件
ul.addEventListener('click', e => {
    if (e.target.className === 'buy') {
        // 获取对应的商品名
        const li = e.target.closest('li');
        const name = li.querySelector('.name').textContent; 

        // 获取用户数据
        const users = JSON.parse(localStorage.getItem('userInfo') || '[]');
        const userIdx = users.findIndex(u => u.username === localStorage.getItem('currentUser'));

        // 将商品添加到对应用户的购物车中
        const shopArr = users[userIdx].shop || [];
        const existItem = shopArr.find(item => item[name]);
        if (existItem) {
            existItem[name] += 1;
        } else {
            shopArr.push({ [name]: 1 });
        }
        users[userIdx].shop = shopArr;
        localStorage.setItem('userInfo', JSON.stringify(users));
        num();
        alert('秒杀成功！请查看您的购物车');
    }
});
let clock2;
function canclick() {
    if (date <= new Date()) {
        for (let i = 0; i < ul.children.length; i++) {
            ul.children[i].children[3].setAttribute("class", "buy")
            ul.children[i].children[3].disabled = false;
            clearInterval(clock2)
        }
    }
    else {
        for (let i = 0; i < ul.children.length; i++) {
            ul.children[i].children[3].setAttribute("class", "no-buy")
            ul.children[i].children[3].disabled = true;
        }
    }
}
clock2 = setInterval(canclick, 1000)

// 购物车数量
function num() {
    const userInfo = JSON.parse(localStorage.getItem("userInfo"))
    const currentUser = localStorage.getItem("currentUser")
    const span = document.querySelector('.top:nth-child(3) span');
    const userIdx = userInfo.findIndex(u => u.username === currentUser);
    const shopArr = userInfo[userIdx].shop;
    let arr = [];
    shopArr.forEach(n => {
        for (let key in n) {
            let value = n[key];
            arr.push(value);
        }
    })
    number = arr.reduce((acc, cur) => acc + cur, 0)
    if (number) {
        span.style.display = "inline-block";
        span.innerText = `${number}`;
    } else {
        span.style.display = "none";
    }
};
num();
